(function() {
  "use strict";
  APP.Views.MainView = Backbone.View.extend({
    events : {
      "contextmenu #menuBase .item": "appContextMenu",
      "click .com-management": "comManagementShow"
    },
    initialize: function() {
      APP.mainView = this;
      this.tiles = {};
      var callback = {
        obj: this,
        name: 'getMenuDataSuccess'
      }
      APP.BeClient.getMenuData(callback, undefined, {
        preloaderShow: false,
        preloaderHide: false
      });
    },
    getMenuDataSuccess: function(data) {
      var self = this;
      this.$el.html(_.template($('#mainTemplate').html(), {}));
      this.$('#menuBase').hide();
      var view = null;
      _.each(data.applications, function(application) {
        view = new APP.Views.TileView({
          application: application
        });
        self.$('#menuBase').append(view.render().el);
        self.tiles[application.id] = view ;
      });
      this.$('#menuBase .item').hide(0);
      this.$('#menuBase').show(0);
      this.showTiles();
      this.attacheDragEndDropMenu();
    },
    saveUserPulpitVisibilitiesSuccess: function(data) {
      var callback = {
        obj: this,
        name: 'getMenuDataUpdateSuccess'
      }
      APP.BeClient.getMenuData(callback, undefined, {hiddenApplicationIds: data.hiddenApplicationIds});
    },
    getMenuDataUpdateSuccess: function(data, options) {
      var self = this;
      _.each(options.hiddenApplicationIds, function(id) {
        if (self.tiles[id] != undefined) {
          self.tiles[id].remove();
          self.tiles[id] = undefined;
        }
      });
      var view = null;
      _.each(data.applications, function(application) {
        if (self.tiles[application.id] == undefined) {
          view = new APP.Views.TileView({
            application: application
          });
          self.$('#menuBase').append(view.render().el);
          self.tiles[application.id] = view;
        }
      });
      this.$('#menuBase').masonry('reload');
      this.saveOrder();
    },
    saveOrder: function() {
      var order = [];
      _.each(this.$('#menuBase .item'), function(item) {
        order.push(parseInt($(item).attr('data-id')));
      });
      APP.BeClient.saveOrder(order, undefined, undefined, {
        preloaderShow: false,
        preloaderHide: false
      });
    },
    showTiles: function() {
      $('#menuBase .item:not(:visible):first').fadeIn(300);
      if ($('#menuBase .item:not(:visible)').length > 0) {
        setTimeout(this.showTiles, 100);
      }
    },
    appMouseUp: function(e) {
      if (e.target.tagName == 'A')
        return;
      if (e.which == 1) {
        var $e = $(e.currentTarget);
        if (!$e.hasClass('dragging'))
          window.open($e.attr('data-url'), "_blank");
      }
    },
    appContextMenu: function(e) {
      e.preventDefault();
      var appId = parseInt($(e.currentTarget).attr('data-id'));
      var menuView = new APP.Views.AppMenuView({
        appId: appId,
        appView: this.tiles[appId],
        menuView: this,
        coord: {
          x: e.pageX,
          y: e.pageY
        }
      });
      $('html').append(menuView.render().el);
      var removeMenu = function() {
        menuView.remove();
        $('body').off('mouseup');
      }
      $('body').on('mouseup', removeMenu);
    },
    attacheDragEndDropMenu: function() {
      var t = this.$('#menuBase');
      var self = this;
      t.masonry({
        itemSelector: '.layout-card',
        isResizable: true,
        columnWidth: 100
      });
      t.sortable({
        items: '.layout-card',
        axis: "xy",
        forcePlaceholderSize: true,
        placeholder: 'card-sortable-placeholder layout-card',
        tolerance: 'pointer',
        opacity: 0.95,
        revert:300,
        start: function(event, ui) {
          self.$('.item').off('mouseup');
          ui.item.addClass('dragging').removeClass('layout-card');
          if ( ui.item.hasClass('long') ) {
            ui.placeholder.addClass('long');
          }
          if ( ui.item.hasClass('vlong') ) {
            ui.placeholder.addClass('vlong');
          }
          ui.item.parent().masonry('reload')
        },
        change: function(event, ui) {
          APP.offset = ui.placeholder.offset();
          ui.item.parent().masonry('reload');
        },
        stop: function(event, ui) {
          ui.item.removeClass('dragging').addClass('layout-card');
          self.$('.item').on('mouseup', self.appMouseUp);
          ui.item.parent().masonry('reload');
          self.saveOrder();
        }
      });
      this.$('.item').on('mouseup', this.appMouseUp);
    },
    renderLoader: function() {
      this.$el.html(_.template($('#mainLoaderTemplate').html(), {}));
      return this;
    }
  });
}());